<?php

$ch[] = curl_init('http://[::]:7777/?1');
$ch[] = curl_init('http://[::]:7777/?2');
$ch[] = curl_init('http://[::]:7777/?3');
$ch[] = curl_init('http://[::]:7777/?4');

$multi = curl_multi_init();

foreach ($ch as $curl) {
    curl_multi_add_handle($multi, $curl);
}


$getStatus = function ($multi) {
    while ($info = curl_multi_info_read($multi)) {
        $uri = curl_getinfo($info['handle'], CURLINFO_EFFECTIVE_URL);
        
        if (CURLMSG_DONE !== $info['msg']) {
            echo "[cURL status] Unknown status: $uri\n";
            continue;
        }
        
        if (CURLE_OK == $info['result']) {
            echo "[cURL status] Done: $uri\n";
            continue;
        }
        
        if (function_exists('curl_strerror')) {
            echo "[cURL status] ", curl_strerror($info['result']), ": $uri\n";
        } else {
            echo "[cURL status] ERROR: $uri\n";
        }
    }
};


$active = null;
do {
    $mrc = curl_multi_exec($multi, $active);
    $getStatus($multi);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($multi) == -1) {
        usleep(100);
    }
    do {
        $mrc = curl_multi_exec($multi, $active);
        $getStatus($multi);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}


foreach ($ch as $curl) {
    if (curl_errno($curl)) {
        // error
        $uri = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
        $error = curl_error($curl);
        echo "[cURL error] $error: $uri\n";
    }
    
    curl_multi_remove_handle($multi, $curl);
    curl_close($curl);
}

curl_multi_close($multi);

echo "Done!\n";


// vim: ts=4 et ai

